package mo.daliy;

import java.util.ArrayList;
import java.util.List;

public class L3133 {

    public long minEnd(int n, int x) {

        List<Integer> xBits = new ArrayList<>(64);
        while (x > 0) {
            xBits.add(x % 2);
            x = x / 2;
        }
        List<Integer> nBits = new ArrayList<>();
        int m = n - 1;
        while (m > 0) {
            nBits.add(m % 2);
            m = m / 2;
        }

        int j = 0;
        for (int i = 0; i < xBits.size(); i++) {
            if (xBits.get(i) == 0) {
                if (j < nBits.size()) {
                    xBits.set(i, nBits.get(j));
                    j++;
                }
            }
        }

        while (j < nBits.size()) {
            xBits.add(nBits.get(j));
            j++;
        }

        long ret = 0;
        for (int i = xBits.size() - 1; i >= 0; i--) {
            ret = ret * 2 + xBits.get(i);
        }

        return ret;
    }

}
